<?php
/*
	Copyright 2006, 2007, 2008, 2009, 2010 Bastiaan Grutters
    
    This file is part of Ages of Strife website.

    Ages of Strife website is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Ages of Strife website is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Ages of Strife website.  If not, see <http://www.gnu.org/licenses/>.
 */
if( !isset( $_POST ) || !isset( $_POST[ 'item_name' ] ) ) {
	print( "This page can't be called directly." );
	exit();
}

$url = "www.paypal.com";
// For testing:
//$url = "www.sandbox.paypal.com";

// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';
foreach ($_POST as $key => $value) {
	$value = urlencode(stripslashes($value));
	$req .= "&$key=$value";
}

// post back to PayPal system to validate
$header =  "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Host: $url:80\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
$fp = fsockopen( "$url", 80, $errno, $errstr, 30 );

// assign posted variables to local variables
if( isset( $_POST[ 'item_name' ] ) ) {
	$item_name = $_POST[ 'item_name' ];
}
else {
	$item_name = "";
}

if( isset( $_POST[ 'item_number' ] ) && is_numeric( $_POST[ 'item_number' ] ) ) {
	$item_number = $_POST[ 'item_number' ];
}
else {
	$item_number = -1;
}

if( isset( $_POST[ 'payment_status' ] ) ) {
	$payment_status = $_POST[ 'payment_status' ];
}
else {
	$payment_status = "";
}

if( isset( $_POST[ 'mc_gross' ] ) ) {
	$mc_gross = $_POST[ 'mc_gross' ];
}
else {
	$mc_gross = 0;
}

if( isset( $_POST[ 'custom' ] ) ) {
	$custom = $_POST[ 'custom' ];
}
else {
	$custom = -1;
}

if( isset( $_POST[ 'mc_currency' ] ) ) {
	$mc_currency = $_POST[ 'mc_currency' ];
}
else {
	$mc_currency = "";
}

if( isset( $_POST[ 'txn_id' ] ) ) {
	$txn_id = $_POST[ 'txn_id' ];
}
else {
	$txn_id = "";
}

/*$business = $_POST['business'];
$payment_currency = $_POST['mc_currency'];
$txn_id = $_POST['txn_id'];
$receiver_email = $_POST['receiver_email'];
$receiver_id = $_POST['receiver_id'];
$quantity = $_POST['quantity'];
$num_cart_items = $_POST['num_cart_items'];
$payment_date = $_POST['payment_date'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$payment_type = $_POST['payment_type'];
$payment_status = $_POST['payment_status'];
$payment_gross = $_POST['payment_gross'];
$payment_fee = $_POST['payment_fee'];
$settle_amount = $_POST['settle_amount'];
$memo = $_POST['memo'];
$payer_email = $_POST['payer_email'];
$txn_type = $_POST['txn_type'];
$payer_status = $_POST['payer_status'];
$address_street = $_POST['address_street'];
$address_city = $_POST['address_city'];
$address_state = $_POST['address_state'];
$address_zip = $_POST['address_zip'];
$address_country = $_POST['address_country'];
$address_status = $_POST['address_status'];
$item_number = $_POST['item_number'];
$tax = $_POST['tax'];
$option_name1 = $_POST['option_name1'];
$option_selection1 = $_POST['option_selection1'];
$option_name2 = $_POST['option_name2'];
$option_selection2 = $_POST['option_selection2'];
$for_auction = $_POST['for_auction'];
$invoice = $_POST['invoice'];
$notify_version = $_POST['notify_version'];
$verify_sign = $_POST['verify_sign'];
$payer_business_name = $_POST['payer_business_name'];
$payer_id = $_POST['payer_id'];
$mc_fee = $_POST['mc_fee'];
$exchange_rate = $_POST['exchange_rate'];
$settle_currency = $_POST['settle_currency'];
$parent_txn_id = $_POST['parent_txn_id'];
$pending_reason = $_POST['pending_reason'];
$reason_code = $_POST['reason_code'];*/

$notify_email = "premium@agesofstrife.com";
$message = "Overview from IPN variables:\r\n\r\n";
$status = "";
$user_id = -1;
$from = -1;
$anonymous = 0;
$turns = -1;
$code = 0;
// 0 = pending
// 1 = complete
// 2 = http error
// 3 = not paid
// 4 = invalid user id
// 5 = invalid product name
// 6 = user id doesn't exist
// 7 = duplicate transaction
// 8 = invalid IPN call
// 9 = wrong currency

include_once( "old_database_connection.php" );

foreach( $_POST AS $key => $value ) {
	$message .= "$key => $value \r\n";
}

//$message .= "\r\n\r\nFsockopen response:\r\n" . $fp;
if( $payment_status == 'Completed' ) {
	if( $mc_currency == 'USD' ) {
		if ( !$fp ) {
			// HTTP ERROR
			$status = "HTTP error with IPN";
			$code = 2;
		} else {
			fputs( $fp, $header . $req );
			while ( !feof( $fp ) ) {
				$res = fgets( $fp, 1024 );
				if ( strcmp($res, "VERIFIED") == 0 ) {
					$query = "SELECT count(*) " .
							"FROM transactions " .
							"WHERE txn_id = '" . addslashes( $txn_id ) . "'";
					$result = mysql_query( $query ) or die( "Query failed : " . mysql_error() );
					$row = mysql_fetch_array( $result, MYSQL_ASSOC );
					
					if( $row[ 'count(*)' ] == 0 ) { 
						$custom = split( '_', $custom );
						if( is_numeric( $custom[0] ) && $custom[0] > 0 && is_numeric( $custom[1] ) && $custom[1] > 0 && is_numeric( $custom[2] ) ) {
							$from = $custom[0];
							$user_id = $custom[1];
							$anonymous = $custom[2];
							$query = "SELECT count(*) " .
									"FROM users " .
									"WHERE user_id = $user_id";
							$result = mysql_query( $query ) or die( "Query failed : " . mysql_error() );
							$row = mysql_fetch_array( $result, MYSQL_ASSOC );
							
							$query2 = "SELECT count(*) " .
									"FROM users " .
									"WHERE user_id = $from";
							$result2 = mysql_query( $query2 ) or die( "Query failed : " . mysql_error() );
							$row2 = mysql_fetch_array( $result2, MYSQL_ASSOC );
							
							if( $row[ 'count(*)' ] == 1 && $row2[ 'count(*)' ] == 1 ) {
								$turns = -1;
								if( $item_name == '1,000 premium turns' && $item_number == 1 && $mc_gross == 2 ) {
									$turns = 1000;
								}
								elseif( $item_name == '3,000 premium turns' && $item_number == 2 && $mc_gross == 5 ) {
									$turns = 3000;
								}
								elseif( $item_name == '6,000 premium turns' && $item_number == 3 && $mc_gross == 9 ) {
									$turns = 6000;
								}
								elseif( $item_name == '12,000 premium turns' && $item_number == 4 && $mc_gross == 17 ) {
									$turns = 12000;
								}
								
								if( $turns > 0 ) {
									$query = "SELECT premium " .
											"FROM users " .
											"WHERE user_id = $user_id";
									$result = mysql_query( $query ) or die( "Query failed : " . mysql_error() );
									$row = mysql_fetch_array( $result, MYSQL_ASSOC );
									$premium = $row[ 'premium' ];
									if( $premium < 0 ) {
										$premium = 0;
									}
									
									$query = "UPDATE users " .
											"SET premium = " . ( $premium + $turns ) . " " .
											"WHERE user_id = $user_id";
									mysql_query( $query ) or die( "Query failed : " . mysql_error() );
									
									$query = "UPDATE game " .
											"SET turns_purchased = ( turns_purchased + $turns ) ";
									mysql_query( $query ) or die( "Query failed : " . mysql_error() );
									
									$ruler = null;
									$from_name = null;
									$query = "SELECT date, turn " .
											"FROM game";
									$result = mysql_query( $query ) or die( "Query failed : " . mysql_error() );
									$row = mysql_fetch_array( $result, MYSQL_ASSOC );
									$date = $row[ 'date' ];
									$turn = $row[ 'turn' ];
									
									$query = "SELECT ruler_id, name " .
											"FROM ruler " .
											"WHERE user_id = $from";
									$result = mysql_query( $query ) or die( "Query failed : " . mysql_error() );
									$row = mysql_fetch_array( $result, MYSQL_ASSOC );
									if( isset( $row[ 'ruler_id' ] ) ) {
										// Send ingame news item
										$ruler_id = $row[ 'ruler_id' ];
										$from_name = $row[ 'name' ];
										
										$subject = "Purchase complete: $item_name";
										$news = "Premium turns overview:\n" .
												"Premium turns before: " . number_format( $premium ) . "\n" .
												"Purchased premium turns: " . number_format( $turns ) . "\n" .
												"Premium turns now: " . number_format( $premium + $turns ) . "\n\n";
										
										if( $from != $user_id ) {
											$query = "SELECT ruler_id, name " .
													"FROM ruler " .
													"WHERE user_id = $user_id";
											$result = mysql_query( $query ) or die( "Query failed : " . mysql_error() );
											$ruler = mysql_fetch_array( $result, MYSQL_ASSOC );
											
											if( isset( $ruler ) && isset( $ruler[ 'name' ] ) ) {
												$to = $ruler[ 'name' ];
												$to2 = $ruler[ 'name' ];
											}
											else {
												$to = "your beneficiary";
												$to2 = "Your beneficiary";
											}
											
											if( $anonymous == 1 ) {
												$news = number_format( $turns ) . " premium turns have been added for " . $to . ".\n" .
													$to2 . " will be notified of the added premium turns without revealing you gave them.\n\n";
											}
											else {
												$news = number_format( $turns ) . " premium turns have been added for " . $to . ".\n" .
													$to2 . " will be notified of the added premium turns and shown they were given by you.\n\n";
											}
										}
										
										$news .= "Thank you for supporting Ages of Strife.\n" .
												 "If you have any question regarding premium turns or your purchase,\nyou can send an ingame letter to <a href=\"../diplomacy/send_letter.php?to=Zworf\">Zworf</a> or send an e-mail to: <a href=\"mailto:premium@agesofstrife.com\">premium@agesofstrife.com</a>.";
										
										$query = "INSERT INTO news " .
												"( ruler_id, type, news, date, subject, seen, turn ) " .
												"VALUES ( $ruler_id, 2, '" . addslashes( $news ) . "', '$date', '" . addslashes( $subject ) . "', 0, $turn )";
										mysql_query( $query ) or die( "Query failed : " . mysql_error() );
									}
									
									if( $ruler_id != $from && isset( $ruler ) && isset( $ruler[ 'ruler_id' ] ) ) {
										$subject = "You have received a gift: $item_name";
										$news = "Premium turns overview:\n" .
												"Premium turns before: " . number_format( $premium ) . "\n" .
												"Received premium turns: " . number_format( $turns ) . "\n" .
												"Premium turns now: " . number_format( $premium + $turns ) . "\n\n";
										if( $anonymous == 1 ) {
											$news .= "He or she who gave you this gift has requested to remain anonymous.\n\n";
										}
										elseif( isset( $from_name ) ) {
											$news .= "The gift is from <a href=\"../overview/ruler.php?name=$from_name\">$from_name</a>.\n\n";
										}
										else {
											$news .= "The gift is from someone without a ruler account.\n\n";
										}
										$news .= "If you have any question regarding premium turns,\nyou can send an ingame letter to <a href=\"../diplomacy/send_letter.php?to=Zworf\">Zworf</a> or send an e-mail to: <a href=\"mailto:premium@agesofstrife.com\">premium@agesofstrife.com</a>.";
										
										$query = "INSERT INTO news " .
												"( ruler_id, type, news, date, subject, seen, turn ) " .
												"VALUES ( " . $ruler[ 'ruler_id' ] . ", 2, '" . addslashes( $news ) . "', '$date', '" . addslashes( $subject ) . "', 0, $turn )";
										mysql_query( $query ) or die( "Query failed : " . mysql_error() );
									}
									
									$status = "VERIFIED IPN: " . number_format( $turns ) . " premium turns added";
									$code = 1;
								}
								else {
									$code = 5;
									$status = "VERIFIED IPN: user_id valid, item name invalid";
								}
							}
							else {
								$code = 6;
								$status = "VERIFIED IPN: user_id doesn't exist";
							}
						}
						else {
							$code = 4;
							$status = "VERIFIED IPN: Invalid user_id";
						}
						
					} else {
						$code = 7;
						$status = "VERIFIED DUPLICATED TRANSACTION";
					}
				}
				else {
					if ( strcmp( $res, "INVALID") == 0 ) {
						$code = 8;
						$status = "INVALID IPN: " . $res;
					}
				}
			}
			fclose( $fp );
		}
	}
	else {
		$status = "Wrong curreny used to pay";
		$code = 9;
	}
}
else {
	$status = "Payment not completed";
	$code = 0;
}

$header2 = 	'From: automatic@agesofstrife.com' . "\r\n" .
			'Reply-To: automatic@agesofstrife.com' . "\r\n" .
			'X-Mailer: PHP/' . phpversion();
mail( $notify_email, 'Purchase: ' . $status, $message, $header2 );

$query = "INSERT INTO transactions " .
		"( `message`, `status`, `user_id`, `turns`, `code`, `item_number`, `item_name`, `txn_id`, `timestamp`, `from`, `anonymous` ) " .
		"VALUES( '" . mysql_real_escape_string( $message ) . "', '" . mysql_real_escape_string( $status ) . "', '$user_id', '$turns', '$code', '$item_number', '" . mysql_real_escape_string( $item_name ) . "', '" . mysql_real_escape_string( $txn_id ) . "', '" . time() . "', '$from', '$anonymous' )";
mysql_query( $query ) or die( "Query failed : " . mysql_error() );
?>
